package com.wjh.mirna.service.impl;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wjh.mirna.dao.LscoreDao;
import com.wjh.mirna.model.Lscore;
import com.wjh.mirna.model.Score;
import com.wjh.mirna.service.LscoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
public class LscoreServiceImpl implements LscoreService {
    @Autowired
    LscoreDao lscoreDao;
    @Override
    public List<String> selectLname() {
        return lscoreDao.selectLname();
    }

    @Override
    public Page queryScore(int pageNum, int size, Lscore score) {
        Page page = new Page<>(pageNum, size);
        List<Lscore> scores = lscoreDao.queryScore(page, score);
        page.setRecords(scores);
        System.out.println(page.getRecords());
        return page;
    }

    @Override
    public void export(Lscore score, HttpServletResponse response) {
        List<Lscore> list = new ArrayList<>();
        if(score.getDname()!=null){
            list = lscoreDao.selectScore(score);
            score.setDname(score.getDname().replace(',',' '));
        }else {
            list = lscoreDao.selectScore(score);
        }
        String filename;
        if(score.getDname() != null){
            filename = score.getDname();
        }else {
            filename = score.getLname();
        }
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        // 设置列宽
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 30);
        writer.setColumnWidth(2, 30);
        writer.setColumnWidth(3, 30);
        // 必须设置，否则多首列
        writer.setOnlyAlias(true);
        // 修改别名
        writer.addHeaderAlias("id", "编号");
        writer.addHeaderAlias("dname", "疾病名称");
        writer.addHeaderAlias("lname", "lncrna名称");
        writer.addHeaderAlias("score", "得分");
        writer.write(list);
        //customer.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
        //out为OutputStream，需要写出到的目标流
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
        } finally {
            writer.flush(out);
            // 关闭writer，释放内存
            writer.close();
        }
    }
}
